<template>
	<view class="main-class">
		<!-- <tn-sticky> -->
			<view class="header-class tn-flex justify-end" >
				<view class="status_bar" style="height: var(--status-bar-height); width: 100%; "></view>			
				<tn-navbar height="45px" home-icon="" :bottom-shadow = "false" bg-color="tn-type-primary_bg" text-color="tn-white" right-operation-width="340" :before-back="beforeBack">任务列表 
					<!-- <template #right>
					      <view class="state_class tn-radius">
							  <view class="">
							  	物流状态
							  </view>
						  </view>
					</template> -->
				</tn-navbar>
			</view>
			<view class="tn-p tn-white_bg">
				<view class="tn-pt-xs">
					结算时间：{{orderInfoData.settledates}}
				</view>	
				<view class="tn-pt-xs">
					单据编号：{{orderInfoData.rfbillcode}}
				</view>	
				<view class="tn-pt-xs">
					客户名称：{{orderInfoData.twobusinessname}}
				</view>	
				<view class="tn-pt-xs">
					地址：{{orderInfoData.address}}
				</view>	
				<view class="tn-pt-xs">
					区域：{{orderInfoData.areaname}}
				</view>	
				<view class="tn-pt-xs">
					支付方式：{{orderInfoData.paytype}}
				</view>
				<view class="tn-pt-xs">
					总金额：{{orderInfoData.taxamount}}
				</view>	
				<view class="tn-pt-xs">
					账期：{{orderInfoData.billing}}
				</view>	
				<view class="tn-pt-xs">
					备注：{{orderInfoData.remark}}
				</view>	
				<br/>
				<view class="tn-flex justify-between">
					<view class=" tn-pr-sm tn-pb-sm tn-text-lg">总单金额：<span class="tn-red-dark_text">￥:{{orderInfoData.taxamount}}</span> </view>
					<view class=" tn-pr-sm tn-pb-sm tn-text-lg">选中金额：<span class="tn-red-dark_text">￥:{{selSumAmount}}</span> </view>
				</view>
				<view class="tn-flex justify-between">
					<tn-radio-group v-model="payTypeValue" border>
					    <tn-radio label="现金">现金</tn-radio>
					    <tn-radio label="线上支付">线上支付</tn-radio>
						<tn-radio label="挂账">挂账</tn-radio>
					</tn-radio-group>
				</view>
			</view>
		<!-- </tn-sticky> -->
		<hr/>
		<view class="tn-pl tn-pr tn-radius tn-pb scroll-view-class">
			<view class="tn-shadow-md tn-pl-sm tn-pt-sm tn-pb-sm"  v-for="(item, index) in orderInfoData.details">
				<view class="tn-flex tn-flex-center-start">
					<view class="tn-w-1-6">
						<tn-switch v-model="item.sel" size="sm" :active-value="1" :inactive-value="0" class="tn-ml-sm" @click="compTMS(item)" :disabled="true" /> 
					</view>
					<view class="tn-w-5-6 tn-flex-column" :style="{'color':item.color}">
						<view class="tn-pt-xs">
							日期：{{item.dates}}
						</view>
						
						<view class="tn-text-xl tn-text-ellipsis-2 tn-pr-xs tn-pt-xs">
							单据编号：{{item.billcode}}
						</view>
						
						<view class="tn-pt-xs">
							金额：{{item.taxamount}}
						</view>
					</view>
				</view>
				
			</view>
		</view>
		<view class="bottom-buttons">
			<view class="">
				<tn-button type="success" size="xl" @click="selAll" >全选</tn-button>
			</view>
			<view class="">
				<tn-button type="success" size="xl" @click="selAdj" >恢复</tn-button>
			</view>
			<view class="">
				<tn-button type="danger" size="xl" @click="toNavigate">提交</tn-button>
			</view>
		</view>
		
		<tn-popup v-model="showPopup">
		    <view class="tn-p-lg popup-class"> 
				<!-- <view class="" v-for="(item, index) in jdStateData " > -->
					<!-- {{item.operationRemark}}
					{{item.operationTime}}
					{{item.operationTitle}} -->
					<!-- <tn-time-line>
						<tn-time-line-item
						v-for="(item, index) in jdStateData"
						 :key="index"
						 :title="item.operationTitle"
						>
							
						</tn-time-line-item>
					</tn-time-line> -->
				<!-- </view> -->
				<cc-defineStep :colors="colors" :stepData="stepData"></cc-defineStep>
			</view>
		</tn-popup>
		<tn-popup v-model="showPopup" close-btn @close="clickPopup">
			<view class="tn-p-lg"> 
				<view class="tn-text-2xl tn-text-center tn-text-bold tn-pb-sm">
					<span>金额:{{selSumAmount}}</span>
				</view>
				<uqrcode ref="uqrcode" canvas-id="qrcode" :value="QrCode" ></uqrcode>
			</view>
		</tn-popup>
		
	</view>
	
	
	
</template>

<script setup>
	import { ref,reactive,onMounted } from 'vue'
	import { postCall,postJD,postKDN,postYinLianPay } from '@/api/index.js'
	import { EventBus } from '@/mitt/EventBus.js';
	import { toastMessage } from '@/utils/toast.js'
	import { createParams,generateUUID16 } from '@/utils/utils.js'
	import Big from 'big.js';
	import dayjs from "dayjs";
	const QrCode = ref(" ");
	const payTypeValue = ref("挂账");
	const procName = "PROC_APP_DO_ORDER";
	const colors = "#fa436a";
	let orderInfoData = reactive({});
	const showPopup = ref(false)
	const jdStateData = reactive([]);
	const stepData = reactive([]);
	const userInfo = reactive({});
	onMounted(()=>{
		const tempOrderInfo = uni.getStorageSync("TMSINFO");
		Object.assign(orderInfoData,tempOrderInfo);
		selSumAmount.value = tempOrderInfo.taxamount;
		Object.assign(userInfo,uni.getStorageSync('USERINFO'));
		payTypeValue.value = orderInfoData.paytype;
	});
	
	const selAll = () =>{	
		for(let i = 0;i<orderInfoData.details.length;i++){
			orderInfoData.details[i].sel = 1;
		}
		compTMS();
	}
	const selSumAmount = ref(0);
	const compTMS = () =>{
		let taxAmount = 0;
		let selAmount = 0;
		for(let i = 0;i<orderInfoData.details.length;i++){
			taxAmount = new Big(taxAmount).plus(new Big(orderInfoData.details[i].taxamount));
			if(orderInfoData.details[i].sel =="1"){
				selAmount = new Big(selAmount).plus(new Big(orderInfoData.details[i].taxamount))
			}
		}
		// taxAmount = taxAmount.toFixed(2);
		orderInfoData.taxamount = taxAmount;
		selSumAmount.value = selAmount;
	} 
	let save = () =>{
		let billcodeList = [];
		for(let j=0;j<orderInfoData.details.length;j++){
			if(orderInfoData.details[j].sel == "1"){
				billcodeList.push(orderInfoData.details[j].billcode.toString());
			}
		}
		
	}
	const billcode = ref("");
	let timer = null;
	let selAdj = () =>{
		let billcodeList = [];
		for(let j=0;j<orderInfoData.details.length;j++){
			if(orderInfoData.details[j].sel == "1"){
				billcodeList.push(orderInfoData.details[j].billcode.toString());
			}
		}
		let params = {};
		params["P_BILLCODES"] = billcodeList.join(",");
		params["P_PROC_NAME"] = "PROC_APP_DO_TMS";
		params["P_PAYTYPEVAL"] = payTypeValue.value;
		params["P_RFBILLCODE"] = orderInfoData.rfbillcode;
		params["P_ACTION"] = "TWOADJ";
		postCall(params).then(res=>{
			if(res){
				if(res.code===200){
					toastMessage("恢复成功！");
				}
			}
		})
	}
	let toNavigate = ()=>{
		let billcodeList = [];
		for(let j=0;j<orderInfoData.details.length;j++){
			if(orderInfoData.details[j].sel == "1"){
				billcodeList.push(orderInfoData.details[j].billcode.toString());
			}
		}
		
		let params = {};
		params["P_BILLCODES"] = billcodeList.join(",");
		params["P_PROC_NAME"] = "PROC_APP_DO_TMS";
		params["P_PAYTYPEVAL"] = payTypeValue.value;
		params["P_RFBILLCODE"] = orderInfoData.rfbillcode;
		params["P_ACTION"] = "TWOCHECK";
		postCall(params).then(res=>{
			if(res){
				if(res.code===200){
				    billcode.value = userInfo.payprefix + ""+ dayjs().format('YYYYMMDDHHmmss')+""+(Math.floor(Math.random() * 900) + 100);
					params["P_ACTION"] = "SAVE";
					params["P_BILLCODE"] = billcode.value;
					postCall(params).then(res=>{
						if(res){
							if(res.code===200){
							    toastMessage("提交成功！");
								if(payTypeValue.value!='线上支付'){
									uni.navigateTo({
									  url: '/pages/delivery/donedelivery' 
									})
								}
							}
						}
					}) 
					if(payTypeValue.value==='线上支付'){
						let dataInfo = {};
						dataInfo.requestTimestamp = dayjs().format('YYYY-MM-DD HH:mm:ss');
						dataInfo.mid = userInfo.mid;
						dataInfo.tid = userInfo.tid;
						dataInfo.instMid = "QRPAYDEFAULT";
						dataInfo.billNo = billcode.value;
						dataInfo.billDate = dayjs().format('YYYY-MM-DD');
						dataInfo.billDesc = billcodeList.join(",");
						dataInfo.totalAmount = new Big(selSumAmount.value).times(100);
						dataInfo.expireTime = dayjs().add(7, 'day').format('YYYY-MM-DD HH:mm:ss');
						// dataInfo.totalAmount = 1;
						dataInfo.notifyUrl = userInfo.payurl;
						let body  = {};
						body.body = dataInfo;
						postYinLianPay(body).then(res=>{
							if(res.data.errMsg){
								toastMessage(res.data.errMsg);
							}
							if(res.data.billQRCode){
								showPopup.value = true;
								QrCode.value = res.data.billQRCode;
							}
							timer = setTimeout(() => {
								queryPayState();
							}, 1000);
						})
					}
				}
			}
		})
		/*
		
		
		 
		
		
		// let params = {};
		// params["P_PROC_NAME"] = "PROC_APP_DO_ORDER";
		// params["P_ACTION"] = "ADDSHOP";
		// params["P_BILLNO"] = orderInfoData.billno;
		// postCall(params).then(res=>{
		// 	if(res){
		// 		if(res.code===200){
		// 		    toastMessage("添加成功！");
		// 			uni.setStorageSync("index",2);
		// 		    uni.navigateTo({
		// 			  url: '/pages/index/index'
		// 		    })
		// 		}
		// 	}
		   
		// })   
		*/
	} 
	const beforeBack = () => {
	  return new Promise((resolve) => {
	    if (timer) {
	    	clearTimeout(timer);
	    }
		resolve(true)
	  })
	}
	let clickPopup = ()=>{
		if (timer) {
			clearTimeout(timer);
		}
	}
	let queryPayState = () =>{
		if (timer) {
			clearTimeout(timer);
		}
		let params = {};
		params["P_PROC_NAME"] = "PROC_APP_DO_PAY";
		params["P_BILLCODE"] = billcode.value;
		params["P_ACTION"] = "QUERY";
		params["isShowLoading"] = false;
		postCall(params).then(res=>{
			if(res.code===200){
				if(res.data.DATASET.length>0){
					if (timer) {
						clearTimeout(timer);
						timer = null;
					}
					showPopup.value = false;
					uni.navigateTo({
					  url: '/pages/delivery/donedelivery'
					})
				}else{
					timer = setTimeout(() => {
						queryPayState();
					}, 1000);
				}
			}else{
				timer = setTimeout(() => {
					queryPayState();
				}, 1000);
			}
		})
	}
	
	let toKdState = (item)=>{
		console.log(item.body);
		showPopup.value = true;
		let params = {};
		params["P_PROC_NAME"] = "PROC_APP_DO_ORDER";
		params["P_ACTION"] = "JD";
		Object.assign(params,JSON.parse(item.body));
		stepData.length = 0;
		// postJD(params).then(res=>{
		// 	if(res){
		// 		if(res.code===200){
		// 			console.log(res.data);
		// 		   if(res.data.code===1000){
		// 			   Object.assign(jdStateData,res.data.data)
		// 			   for(let i = 0 ;i<res.data.data.length;i++){
		// 				   let item = {};
		// 				   item.name = res.data.data[i].operationTitle;
		// 				   item.time = res.data.data[i].operationTime;
		// 				   item.isNow = 0;
		// 				   item.type = 1;
		// 				   item.desc = res.data.data[i].operationRemark;
		// 				   stepData.push(item)
		// 			   }
		// 			   stepData.sort(function(a,b){
		// 				   let dateA = new Date(a.time);
		// 				   let dateB = new Date(b.time);
		// 				   return dateB-dateA;
		// 			   })
		// 			   if(stepData.length>0){
		// 				   stepData[0].isNow = 1;
		// 			   }
		// 			   stepData.forEach(function(operation) {
		// 			     console.log(operation);
		// 			   });
		// 		   }else{
		// 			   toastMessage(res.data.message);
		// 		   }
		// 		}
		// 	}
		// })   
		params["P_ACTION"] = "KDN";
		postKDN(params).then(res=>{
			if(res){
				if(res.code===200){
					console.log(res.data);
				   if(res.data.Success){
					   Object.assign(jdStateData,res.data.Traces)
					   for(let i = 0 ;i<res.data.Traces.length;i++){
						   let item = {};
						   item.name = res.data.Traces[i].AcceptStation;
						   item.time = res.data.Traces[i].AcceptTime;
						   item.isNow = 0;
						   item.type = 1;
						   item.desc = res.data.Traces[i].Location;
						   stepData.push(item)
					   }
					   stepData.sort(function(a,b){
						   let dateA = new Date(a.time);
						   let dateB = new Date(b.time);
						   return dateB-dateA;
					   })
					   if(stepData.length>0){
						   stepData[0].isNow = 1;
					   }
					   stepData.forEach(function(operation) {
					     console.log(operation);
					   });
				   }else{
					   toastMessage(res.data.Reason);
				   }
				   
				}
			}
		})   
	}
	
	let coypText = (info) =>{
		uni.setClipboardData({
			data: info,//要被复制的内容
			success:() => {//复制成功的回调函数
				uni.showToast({//提示
					title:'复制成功' 
				})
			}
		});
	}
	
	
	// let sortTime = (a,b) =>{
	// 	return a.time - b.time
	// }
	
	// let getKdInfo = ()=>{
	// 	let params = {};
	// 	params["P_PROC_NAME"] = "PROC_APP_DO_ORDER";
	// 	params["P_ACTION"] = "JD";
	// 	postCall(params).then(res=>{
	// 		if(res){
	// 			if(res.code===200){
				    
	// 			}
	// 		}
	// 	}) 
	// }
	
</script>

<style scoped>
.header-class{
	height: 17vh !important;
	flex-direction: column
}
.form-class{
	width: 90vw;
	margin-left: 5vw;
}
.button-class{
	margin-top: 5vh;
	width: 90vw;
	border-radius: 40px !important;
	/* color: #FFFFFF !important; */
	background: linear-gradient(to right,  #47e8be,#3379dc);
	/* border: 0px solid rgba(0, 0, 0, 0.2) !important; */
}

.bottom-buttons {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	background-color: #fff; /* 设置底部背景色 */
	padding: 10px; /* 设置内边距 */
	display: flex;
	justify-content: space-between;
	box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1); /* 设置底部阴影 */
	padding-bottom: calc(env(safe-area-inset-bottom) + 20px);
	height: 8vh;
}

.scroll-view-class{
	padding-bottom: 8.5vh;
}

.button-class::after{
	border: 0px solid rgba(0, 0, 0, 0.2) !important;
}

.popup-calendar-button {
  margin: 0rpx 30rpx;
  width: calc(100% - 60rpx) !important;
  padding: 20rpx 30rpx !important;
}

.no-data-class{
	
	display: flex;
	justify-content: center;
	align-items: center;
	padding-top: 10vh;
}
/* .state_class{
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: rgba(0, 0, 0, 0.15);
	color: #fff;
	z-index: 20090;
	width: 87px;
	height: 32px;
	right: 10px;
} */

/* .popup-class{
	width: 80vw;
	height: 60vh;
	overflow-y: auto;
} */
</style>
